import React, { Suspense } from "react";

import { Switch, Route, Redirect } from "react-router-dom";


function RouterView(props) {
    
    var { routes } = props;
    // console.log(routes);
    //获取当前路由的权限
    var permissions=localStorage.getItem('userinfo')?JSON.parse(localStorage.getItem('userinfo')).role.permissions:[];



    //过滤普通路由(过滤当前用户有权限访问的路由)
    var normalRoutes = routes.filter((item) => {
        return item.path && item.component && !item.permission_no||item.path&&item.component&&permissions.some((permi)=>permi===item.permission_no);
    })

    //过滤重定向路由表
    var redirectRoutes = routes.filter((item) => {
        return item.from&&item.to;
    })

    //过滤路由表中的404路由
    var notfoundRoutes = routes.filter((item) => {
        return item.component && !item.path;
    })
    return (
        <Suspense fallback={<>loading...</>}>
            <Switch>
            {/* 渲染Route普通路由规则 */}
            {
                normalRoutes.map((item, index) => {
                    return (
                        <Route key={index} exact={item.exact || false} path={item.path} render={(props) => {
                            if (item.children && item.children.length > 0) {
                                return <item.component {...props} routes={item.children}></item.component>
                            }else{
                                return <item.component {...props}></item.component>
                            }
                        }
                        }>

                        </Route>
                    )
                })
            }
            {/* 渲染重定向路由 */}
            {
                redirectRoutes.map((item,index)=>{
                    return(
                        <Redirect key={index} exact from={item.from} to={item.to}></Redirect>
                    )
                })
            }
            {/* 渲染Route  404路由规则 */}
            {
                notfoundRoutes.map((item,index)=>{
                    return (
                        <Route key={index} component={item.component}></Route>
                    )
                })
            }
            </Switch>
        </Suspense>
    );
}

export default RouterView;